package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.AttrKey;
import com.atguigu.lease.model.entity.AttrValue;
import com.atguigu.lease.web.admin.mapper.AttrKeyMapper;
import com.atguigu.lease.web.admin.service.AttrKeyService;
import com.atguigu.lease.web.admin.service.AttrValueService;
import com.atguigu.lease.web.admin.vo.attr.AttrKeyVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gqs
 * @description 针对表【attr_key(房间基本属性表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class AttrKeyServiceImpl extends ServiceImpl<AttrKeyMapper, AttrKey>
    implements AttrKeyService {
  @Autowired private AttrKeyMapper attrKeyMapper;
  @Autowired private AttrValueService attrValueService;

  @Override
  public List<AttrKeyVo> listAttrInfo() {
    List<AttrKeyVo> attrKeyVoList = attrKeyMapper.listAttrInfo();
    return attrKeyVoList;
  }

  @Override
  public boolean saveOrUpdateAttrKey(AttrKey attrKey) {
    Long id = attrKey.getId() == null ? -1 : attrKey.getId();
    AttrKey dbAttrKey =
        this.getOne(
            Wrappers.lambdaQuery(AttrKey.class)
                .eq(AttrKey::getName, attrKey.getName())
                .last("limit 1"));
    if (dbAttrKey == null || dbAttrKey.getId().equals(id)) {
      return this.saveOrUpdate(attrKey);
    }
    throw new StgyException(ResultCodeEnum.ATTR_KEY_EXISTS_ERROR);
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public boolean removeAllById(Long attrKeyId) {
    this.removeById(attrKeyId);
    boolean flag = attrValueService.remove(Wrappers.lambdaQuery(AttrValue.class)
            .eq(AttrValue::getAttrKeyId, attrKeyId));
    return flag;
  }
}
